﻿--------------------------------------------------------------------------
-- Licensed under GNU General Public License version 2 (GPLv2)
-- TPL Helper Library by DHGMS Solutions
-- http://tplhelper.codeplex.com
--------------------------------------------------------------------------

SELECT
	CAST(
	CASE
		WHEN
			(
				@sinceDate IS NOT NULL
				AND MAX(UNPIVOTED.FieldValue) IS NOT NULL
				AND MAX(UNPIVOTED.FieldValue) > @sinceDate
			)
			OR (
				@sinceDate IS NOT NULL
				AND MAX(UNPIVOTED.FieldValue) IS NULL
				AND CAST(@sinceDate AS DATE) <> CAST(GETDATE() AS DATE)
				)
			OR @sinceDate IS NULL THEN 1
		ELSE 0
		END AS BIT) AS UPDATENEEDED
FROM
(
	select
		tab.create_date
		,tab.modify_date
		,indstats.last_system_update
		,indstats.last_user_update
	from sys.indexes as ind
	inner join sys.tables as tab on
		tab.object_id = ind.object_id
	inner join sys.dm_db_index_usage_stats as indstats on
		indstats.object_id = tab.object_id
	where ind.is_primary_key = 1
		and tab.name = @tableName
) AS PIVOTED
UNPIVOT(
	FieldValue FOR FieldCode IN (
		create_date,
		modify_date,
		last_system_update,
		last_user_update
		)
	) AS UNPIVOTED
